import re

from rest_framework import serializers
from product.models import ProductCategory, Product, User


# The original model object serializer
# class ProductCategorySerializer(serializers.Serializer):
#     name = serializers.CharField(required=True)
#     title = serializers.CharField(required=True)
#     image = serializers.ImageField(required=False)
#     parent = serializers.SerializerMethodField()
#
#     def get_parent(self, instance):
#         if instance.parent:
#             m = ProductCategorySerializer(instance.parent)
#             return m.data
#             # return instance.parent.pk
#
#     def create(self, validated_data):
#         c = ProductCategory()
#         c.name = validated_data['name']
#         c.title = validated_data['title']
#         c.image = validated_data['image']
#         c.save()
#         return c
#
#     def update(self, instance, validated_data):
#         # for key in validated_data.keys():
#         #     setattr(instance, key, validated_data[key])
#
#         instance.name = validated_data.get("name", instance.name)
#         instance.title = validated_data.get("title", instance.title)
#         instance.save(force_update=True)
#         return instance

class ProductCategorySerializer(serializers.ModelSerializer):
    children = serializers.SerializerMethodField()

    # 序列化子对象，该过程可能会被嵌套调用，小心使用
    def get_children(self, instance):
        children = ProductCategory.objects.filter(parent=instance)
        children_set = [ProductCategorySerializer(instance=c).data for c in children]
        return children_set

    class Meta:
        model = ProductCategory
        exclude = ()


class ProductSerializer(serializers.ModelSerializer):
    category = serializers.SerializerMethodField()

    # 序列化外键应用的对象
    def get_category(self, instance):
        return ProductCategorySerializer(instance=instance.category).data

    class Meta:
        model = Product
        exclude = ()


class UserSerializer(serializers.ModelSerializer):
    # 用于验证TELEPHONE字段是否符合规范。
    def validate_telephone(self, value):
        pattern = "^1[0-9]{10}$"
        if not re.match(pattern, value):
            raise serializers.ValidationError("Your telephone is invalid")
        return value

    # 用于对象级别验证方法。
    def validate(self, attrs):
        # TODO: add code here to validate some policies
        return attrs

    class Meta:
        model = User
        exclude = ("salt",)
